'Copyright (C) 2009 Christiaan Cable
'
'This program is free software; you can redistribute it and/or
'modify it under the terms of the GNU General Public License
'as published by the Free Software Foundation; either version 3
'of the License, or (at your option) any later version.
'
'This program is distributed in the hope that it will be useful,
'but WITHOUT ANY WARRANTY; without even the implied warranty of
'MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
'GNU General Public License for more details (LICENCE.TXT).

Imports System.Windows.Forms

Public Class SuperNerd
    Public ISPReturnData As New ISPReturnData
    Private CookieContainer As New System.Net.CookieContainer

    Public Sub New(ByVal ConfigurationData As ConfigurationData)

        Try
            'set rollover date
            SetRolloverDate(ConfigurationData, ISPReturnData)

            Dim strHTMLData As String

            'login 
            Dim POSTData As String = "username=" & ConfigurationData.Username & "&password=" & ConfigurationData.Password & "&login=Enter&my_account_login="
            strHTMLData = ISPPost("https://www.supernerd.com.au/index2.cfm?action=members&type=account", POSTData, CookieContainer, System.Net.CredentialCache.DefaultCredentials)


            If strHTMLData.Contains("Error Message") = True Then
                ISPReturnData.ErrorMessage = "Login Failed"
                Exit Sub
            End If

            'get usage page
            strHTMLData = ISPGet("https://www.supernerd.com.au/index2.cfm?action=members&type=account&page=members_usage", CookieContainer, System.Net.CredentialCache.DefaultCredentials)

            'extract service type
            Dim ServiceOptions As String = ExtractText(strHTMLData, "<select name=""selected_rgid""", 0, ">", "</select>")

            'extract each option
            Dim ServiceID As String = ""
            Dim Start As Integer = 1
            Dim Finish As Integer = 0
            Dim strTemp As String
            Do
                Start = InStr(Start, ServiceOptions, "<option value=""", CompareMethod.Text)
                If Start = 0 Then Exit Do
                Finish = InStr(Start + 14, ServiceOptions, "</option>", CompareMethod.Text)
                If Finish = 0 Then Exit Do
                strTemp = Mid(ServiceOptions, Start + 15, Finish - Start - 15).ToLower
                If strTemp.Contains("dsl") Then
                    ServiceID = Left(strTemp, InStr(strTemp, """") - 1)
                    Exit Do
                End If
                Start = Finish + 9
                If Start > Len(ServiceOptions) + 1 Then Exit Do
            Loop

            If ServiceID = "" Then
                ISPReturnData.ErrorMessage = "Unable to determine serivce number"
                Exit Sub
            End If

            'usage
            POSTData = "selected_rgid=" & ServiceID & "&start_day=" & ISPReturnData.RolloverDate.Day & "&start_month=" & ISPReturnData.RolloverDate.Month & "&start_year=" & ISPReturnData.RolloverDate.Year & "&end_day=" & ISPReturnData.RolloverDate.AddMonths(1).AddDays(-1).Day & "&end_month=" & ISPReturnData.RolloverDate.AddMonths(1).AddDays(-1).Month & "&end_year=" & ISPReturnData.RolloverDate.AddMonths(1).AddDays(-1).Year & "&Submit=Submit"
            strHTMLData = ISPPost("https://www.supernerd.com.au/index2.cfm?action=members&type=account&page=members_usage", POSTData, CookieContainer, System.Net.CredentialCache.DefaultCredentials)

            If UA.DebugISP = True Then My.Computer.FileSystem.WriteAllText(GetAppDataPath() & "debug.htm", strHTMLData, False, System.Text.Encoding.ASCII)

            'logout
            ISPGet("https://www.supernerd.com.au/index2.cfm?action=members&type=account&page=log_out", CookieContainer, System.Net.CredentialCache.DefaultCredentials)

            '##################################################################################

            'process response
            ISPReturnData.PeakDownload = CSng(Val(Replace(ExtractText(strHTMLData, "Total ", 0, ":", "MB"), ",", "")))
            ISPReturnData.LastUpdated = Now

            '##########################################################

            ProcessISPData(ConfigurationData, ISPReturnData)

            'check for error
            If ISPReturnData.ErrorMessage <> "" Then Exit Sub

            '##########################################################

            'create graph data
            ISPReturnData.GraphItemList.Add(New GraphItem("Peak " & Format(System.Math.Floor((ISPReturnData.PeakDownload / Val(ConfigurationData.PeakUsageLimit)) * 1000) / 10, "#0.0") & "% (" & ISPReturnData.PeakDownload & " MB)", ISPReturnData.PeakDownload, CSng(Val(ConfigurationData.PeakUsageLimit)), False))

            'days elapsed
            ISPReturnData.GraphItemList.Add(New GraphItem("Days Elapsed " & Format((ISPReturnData.DaysUsed / (ISPReturnData.DaysUsed + ISPReturnData.DaysLeft)) * 100, "#0") & "% (" & ISPReturnData.DaysUsed & " Days)", ISPReturnData.DaysUsed, ISPReturnData.DaysUsed + ISPReturnData.DaysLeft, False))

            '##########################################################

            'create stats data
            ISPReturnData.TextItemList.Add(New TextItem("Peak Left :", ISPReturnData.PeakUsageRemainingDescription))
            ISPReturnData.TextItemList.Add(New TextItem("Peak Avg. Left :", ISPReturnData.PeakUsageRemainingPerDayDescription))

            If ISPReturnData.ShapedNow = False Then
                ISPReturnData.TextItemList.Add(New TextItem("Shaped :", "NO"))
            Else
                ISPReturnData.TextItemList.Add(New TextItem("Shaped :", "YES"))
            End If

            '##########################################################

            'process alerts
            ProcessAlerts(ConfigurationData, ISPReturnData)

        Catch ex As Exception
            ISPReturnData.ErrorMessage = ex.Message
        End Try

    End Sub

End Class
